package com.security.springsecuritylearn02.config;

import com.security.springsecuritylearn02.entity.MyUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

/**
 * @author llj
 * @create 2022-06-28 14:19
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private MyPasswordEncoder myPasswordEncoder;

    @Autowired
    MyUserDetailsService myUserDetailsService;
    @Autowired
    MyAccessHandle myAccessHandle;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //放行静态资源
        http.authorizeRequests().antMatchers("/showLogin","/style.css").permitAll()
                .antMatchers("/admin").hasAnyRole("USER","ADMIN")
                //accessDeniedHandler 权限不足处理
                .antMatchers("/user").hasRole("USER").and().exceptionHandling().accessDeniedHandler(myAccessHandle)
                .and().authorizeRequests().and().csrf().disable();
        //loginProcessingUrl必须有不然的话无法登录赋值权限（登录处理地址）必须处理表单发送的地址，loginPage是自定义登录页面样式
        http.formLogin().loginPage("/showLogin").loginProcessingUrl("/userLogin").successForwardUrl("/hello");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService).passwordEncoder(myPasswordEncoder);
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new MyPasswordEncoder();
    }
}
